package com.light.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.light.common.utils.R;
import com.light.common.vo.MemberRespVO;
import com.light.gulimall.auth.config.GulimallOAuthConfig;
import com.light.gulimall.auth.dto.SocialUser;
import com.light.gulimall.auth.feign.MemberRemoteFeignClient;
import com.light.gulimall.auth.util.HttpUtils;
import jdk.internal.org.objectweb.asm.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Controller
@Slf4j
public class OAuth2Controller {

    @Autowired
    private GulimallOAuthConfig authConfig;

    @Autowired
    private MemberRemoteFeignClient memberRemoteFeignClient;

    @GetMapping("/oauth2.0/gitee/success")
    public String auth2Login(@RequestParam("code") String code, HttpSession session) throws Exception {
        //code是前端传入的
        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "authorization_code");
        map.put("code", code);
        map.put("client_id", authConfig.getClientId());
        map.put("redirect_uri", authConfig.getRedirectUri());
        map.put("client_secret", authConfig.getClientSecret());

        //应用服务器 或 Webview 使用 access_token API 向 码云认证服务器发送post请求传入 用户授权码 以及 回调地址（ POST请求 ）
        //根据code拿到授权码（access_token）
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());

        R login = null;
        //得到access_token
        if (response.getStatusLine().getStatusCode() == 200) {
            String s = EntityUtils.toString(response.getEntity());
//            System.out.println(s);
            SocialUser socialUser = JSON.parseObject(s, SocialUser.class);

            //远程调用member服务，进行社交登录逻辑（根据授权码获取用户信息）
            login = memberRemoteFeignClient.login(socialUser);
            int loginCode = (int) login.get("code");
            if (loginCode != 0) {
                //登录失败
                return "redirect:http://auth.gulimall.com/login.html";
            }

        } else {
            //登录失败
            return "redirect:http://auth.gulimall.com/login.html";
        }
        //整合springSession解决session共享问题
        //session共享问题：域名不同，或者同一域名但是多个服务器
        LinkedHashMap data = (LinkedHashMap) login.get("data");
        ObjectMapper objectMapper = new ObjectMapper();
        MemberRespVO memberRespVO = objectMapper.convertValue(data, MemberRespVO.class);
        log.info("登录成功：{}",memberRespVO.toString());
        session.setAttribute("loginUser",memberRespVO);
        return "redirect:http://gulimall.com";
    }

}
